package com.ruipeng.shengyapo.controller;

import com.ruipeng.shengyapo.comm.Page;
import com.ruipeng.shengyapo.comm.ResponseData;
import com.ruipeng.shengyapo.model.UserInfo;
import com.ruipeng.shengyapo.pay.alipay.config.AlipayConfig;
import com.ruipeng.shengyapo.pay.alipay.util.AlipayNotify;
import com.ruipeng.shengyapo.pay.wx.*;
import com.ruipeng.shengyapo.service.OrderService;
import com.ruipeng.shengyapo.service.UserService;
import com.ruipeng.shengyapo.utils.*;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.NameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.AbstractDocument;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;

/**
 * Created by tu_pei on 17/5/28.
 * 用户相关
 */
@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private OrderService orderService;

    /**
     * 查询用户
     * url/user/{userId}
     * @param userId 用户ID
     * @return
     */
    @RequestMapping(value = "/{userId}/info",method = RequestMethod.POST)
    @ResponseBody
    public ResponseData getByUserId(@PathVariable int userId){
        ResponseData data = new ResponseData();
        if(ObjUtils.isNotEmpty(userId)){
            Map<String,Object> userMap = userService.getByUserId(userId);
            data.setResults(userMap);
            data.setState(ContentUtils.COMM_STATE_TRUE);
            return data;
        }else{
            data.setMsg("用户不存在");
            data.setState(ContentUtils.COMM_STATE_FALSE);
            return data;
        }
    }

    /**
     * 修改用户
     * url/user/update
     * @return
     */
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    @ResponseBody
    public ResponseData updateAllByUserId( UserInfo user){
        ResponseData data = new ResponseData();
        Map<String, Object> map;
		try {
			map = BeanToMapUtil.convertBean(user);
			 int count = userService.updateUserInfo(map);
		        if( count > 0 ){
                    data.setResults(user);
                    data.setState(ContentUtils.COMM_STATE_TRUE);
		            return data;
		        }else{
		            //保存失败
		            data.setMsg("用户信息修改失败");
                    data.setState(ContentUtils.COMM_STATE_FALSE);
		            return data;
		        }
		} catch (Exception e) {
			e.printStackTrace();
		} 
		 data.setMsg("用户信息修改失败");
         return data;
    }

    /**
     * 获取用户行程
     * url/user/trip/{userId}
     * @param userId
     * @return
     */
    @RequestMapping(value = "/trip/{userId}",method = RequestMethod.POST)
    @ResponseBody
    public ResponseData getUserTrip(@PathVariable int userId){
        ResponseData data = new ResponseData();
        
        if(ObjUtils.isNotEmpty(userId)){
            data.setState(ContentUtils.COMM_STATE_TRUE);
            data.setResults(userService.getUserTrip(userId));
            return data;
        }else{
            data.setState(ContentUtils.COMM_STATE_FALSE);
            data.setMsg("用户不存在");
            return data;
        }
    }

    /**
     * 获取行程详情
     * url/user/trip/{tripId}/info
     * @param tripId
     * @return
     */
    @RequestMapping(value = "/trip/{tripId}/info",method = RequestMethod.POST)
    @ResponseBody
    public ResponseData getuserTripInfo(@PathVariable int tripId){
        ResponseData data = new ResponseData();
        Map<String,Object> params = new HashMap<String,Object>();

        if(ObjUtils.isNotEmpty(tripId)){
            params.put("tripId",tripId);
            data.setState(ContentUtils.COMM_STATE_TRUE);
            data.setResults(userService.getuserTripInfo(params));
            return data;
        }else{
            data.setState(ContentUtils.COMM_STATE_FALSE);
            data.setMsg("获取信息失败");
            return data;
        }
    }
    //商户相关资料
    public static final String appid = "wx7b14fffaff032ed6";//在微信开发平台登记的app应用
    public static final String appsecret = "4272c7fcca4f83874d49d1257560f0ce";
    public static final String partner = "1480763132";//商户号
    public static final String partnerkey ="shengyabo1234567890shengyabo1234";//不是商户登录密码，是商户在微信平台设置的32位长度的api秘钥，
    public static final String createOrderURL="https://api.mch.weixin.qq.com/pay/unifiedorder";
    public static final String notifyUrl="http://59.110.235.98:80/sypappservice/notifyUrl";//异步通知地址
    /**
     * 生成订单号
     * @param userId
     * @param rechargeType
     * @param rechgrgeAmount
     * @param rechargeWay
     * @return
     */
    @RequestMapping(value = "{userId}/recharge",method = RequestMethod.POST)
    @ResponseBody
    public ResponseData createOrderInfo(HttpServletRequest request, HttpServletResponse response, @PathVariable int userId, String rechargeType, double rechgrgeAmount, String rechargeWay)throws Exception{
        ResponseData data = new ResponseData();

        Map<String,Object> orderParamsMap = new HashMap<String,Object>();
        orderParamsMap.put("userId",userId);
        orderParamsMap.put("rechargeType",rechargeType);
        orderParamsMap.put("rechargeWay",rechargeWay);
        orderParamsMap.put("rechgrgeAmount",rechgrgeAmount);
        orderParamsMap.put("tradeInfo",null);
        orderParamsMap.put("tradeStatus",0);
        orderParamsMap.put("otherNo","");

        //判断用户是否交押金

        Map<String,Object> userMap = userService.getByUserId(userId);
        if(userMap.get("deposit").toString().equals("0")){
            data.setState(ContentUtils.COMM_STATE_FALSE);
            data.setMsg("该用户已交押金");
            return data;
        }
        String detail = "";
        if(rechargeWay.equals("0")){
            String json=null;

            JSONObject retMsgJson=new JSONObject();
            //金额转化为分为单位
            float sessionmoney = Float.parseFloat(String.valueOf(rechgrgeAmount));
            String finalmoney = String.format("%.2f", sessionmoney);
            finalmoney = finalmoney.replace(".", "");
            String currTime = TenpayUtil.getCurrTime();
            //8位日期
            String strTime = currTime.substring(8, currTime.length());
            //四位随机数
            String strRandom = TenpayUtil.buildRandom(4) + "";
            //10位序列号,可以自行调整。
            String strReq = strTime + strRandom;
            //商户号
            String mch_id = partner;
            //子商户号  非必输
            //String sub_mch_id="";
            //设备号   非必输
            String device_info="";
            //随机数
            String nonce_str = strReq;
            String body = "充值";
            //附加数据
            String attach = String.valueOf(userId);
            //商户订单号
            String out_trade_no = ObjUtils.getNowDate() + ObjUtils.randomNumeric(4)+"00100"+ObjUtils.randomNumeric(6)+"00"+ObjUtils.randomNumeric(4);
            //String out_trade_no = ObjUtils.getNowDate() + NumberUtils.getRandomCharAndNumr(24);
            int intMoney = Integer.parseInt(finalmoney);
            //总金额以分为单位，不带小数点
            String total_fee = String.valueOf(intMoney);
            //订单生成的机器 IP
            String spbill_create_ip = request.getRemoteAddr();
            String notify_url = notifyUrl;//微信异步通知地址
            String trade_type = "APP";//app支付必须填写为APP
            //对以下字段进行签名
            SortedMap<String, String> packageParams = new TreeMap<>();
            packageParams.put("appid", appid);
            packageParams.put("attach", attach+","+rechargeType);
            packageParams.put("body", body);
            packageParams.put("mch_id", mch_id);
            packageParams.put("nonce_str", nonce_str);
            packageParams.put("notify_url", notify_url);
            packageParams.put("out_trade_no", out_trade_no);
            packageParams.put("spbill_create_ip", spbill_create_ip);
            packageParams.put("total_fee", total_fee);
            packageParams.put("trade_type", trade_type);
            RequestHandler reqHandler = new RequestHandler(request, response);
            reqHandler.init(appid, appsecret, partnerkey);
            String sign = reqHandler.createSign(packageParams);//获取签名
            String xml="<xml>"+
                    "<appid>"+appid+"</appid>"+
                    "<attach>"+attach+","+rechargeType+"</attach>"+
                    "<body><![CDATA["+body+"]]></body>"+
                    "<mch_id>"+mch_id+"</mch_id>"+
                    "<nonce_str>"+nonce_str+"</nonce_str>"+
                    "<notify_url>"+notify_url+"</notify_url>"+
                    "<out_trade_no>"+out_trade_no+"</out_trade_no>"+
                    "<spbill_create_ip>"+spbill_create_ip+"</spbill_create_ip>"+
                    "<total_fee>"+total_fee+"</total_fee>"+
                    "<trade_type>"+trade_type+"</trade_type>"+
                    "<sign>"+sign+"</sign>"+
                    "</xml>";
            String prepay_id="";
            try {
                String reslut = HttpUtils.sendPost(createOrderURL,xml);
                System.out.println("reslut="+reslut);
                prepay_id = reslut.substring(reslut.indexOf("<prepay_id><![CDATA[")+20,reslut.indexOf("]]></prepay_id>"));
                System.out.println("prepay_id="+prepay_id);
                if(prepay_id.equals("")){
                    data.setState(ContentUtils.COMM_STATE_FALSE);
                    data.setMsg("error");
                    return data;
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            //获取到prepayid后对以下字段进行签名最终发送给app
            SortedMap<String, String> finalpackage = new TreeMap<String, String>();
            String timestamp = Sha1Util.getTimeStamp();
            finalpackage.put("appid", appid);
            finalpackage.put("timestamp", timestamp);
            finalpackage.put("noncestr", nonce_str);
            finalpackage.put("partnerid", partner);
            finalpackage.put("package", "Sign=WXPay");
            finalpackage.put("prepayid", prepay_id);
            finalpackage.put("out_trade_no",out_trade_no);
            String finalsign = reqHandler.createSign(finalpackage);
            retMsgJson.put("msg", "ok");
            retMsgJson.put("trade_type_syb", rechargeType);
            retMsgJson.put("appid", appid);
            retMsgJson.put("attach",userId);
            retMsgJson.put("timestamp", timestamp);
            retMsgJson.put("noncestr", nonce_str);
            retMsgJson.put("partnerid", partner);
            retMsgJson.put("prepayid", prepay_id);
            retMsgJson.put("package", "Sign=WXPay");
            retMsgJson.put("sign", finalsign);
            retMsgJson.put("orderInfo", finalsign);
            retMsgJson.put("out_trade_no",out_trade_no);
            data.setState(ContentUtils.COMM_STATE_TRUE);
            data.setResults(retMsgJson);

            //orderService.addOrderInfo(orderParamsMap);

            return data;
        }else {
            Map<String,Object> orderMap = orderService.addOrderInfo(orderParamsMap);
            data.setState(ContentUtils.COMM_STATE_TRUE);
            //支付宝支付
            if(rechargeType.equals("1")){
                detail = "充值";
            }
            if(rechargeType.equals("2")){
                detail = "交押金";
            }
            if(rechargeType.equals("3")){
                detail = "退押金";
            }
            boolean rsa2 = (AlipayConfig.private_key.length() > 0);
            Map<String, String> params = AlipayNotify.buildOrderParamMap(AlipayConfig.APP_ID, rsa2, String.valueOf(rechgrgeAmount), detail, orderMap.get("rechgId").toString());
            String orderParam = AlipayNotify.buildOrderParam(params);

            String privateKey = AlipayConfig.private_key;
            String sign = AlipayNotify.getSign(params, privateKey, rsa2);
            final String orderInfo = orderParam + "&" + sign;
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("orderInfo",orderInfo);
            data.setResults(map);
            return data;
        }
    }

    /**
     * 从Request对象中获得客户端IP，处理了HTTP代理服务器和Nginx的反向代理截取了ip
     * @param request
     * @return ip
     */
    public static String getLocalIp(HttpServletRequest request) {
        String remoteAddr = request.getRemoteAddr();
        String forwarded = request.getHeader("X-Forwarded-For");
        String realIp = request.getHeader("X-Real-IP");

        String ip = null;
        if (realIp == null) {
            if (forwarded == null) {
                ip = remoteAddr;
            } else {
                ip = remoteAddr + "/" + forwarded.split(",")[0];
            }
        } else {
            if (realIp.equals(forwarded)) {
                ip = realIp;
            } else {
                if(forwarded != null){
                    forwarded = forwarded.split(",")[0];
                }
                ip = realIp + "/" + forwarded;
            }
        }
        return ip;
    }
    @RequestMapping(value = "/updateOrder",method = RequestMethod.POST)
    @ResponseBody
    public ResponseData userUpdateOrder(int userId,int ridingId,int ridingDistance,int ridingTime,int carbonSaving,int consumeKcal,String ridingPaths){
        ResponseData data = new ResponseData();
        if(ObjUtils.isEmpty(userId) || ObjUtils.isEmpty(ridingDistance) || ObjUtils.isEmpty(ridingTime)||
        ObjUtils.isEmpty(carbonSaving) || ObjUtils.isEmpty(consumeKcal) || ObjUtils.isEmpty(ridingPaths)){
            data.setState(ContentUtils.COMM_STATE_FALSE);
            data.setMsg("缺少参数");
            return data;
        }else{
            Map<String,Object> params = new HashMap<String,Object>();
            params.put("riingOrderId",ridingId);
            Map<String,Object> maps = orderService.getUserRidingPaths(ridingId);
            if(ObjUtils.isEmpty(maps)){
                params.put("userId",userId);
                params.put("ridingOrderId",ridingId);
                params.put("ridingDistance",ridingDistance);
                params.put("ridingTime",ridingTime);
                params.put("carbonSaving",carbonSaving);
                params.put("consumeKcal",consumeKcal);
                params.put("ridingPaths",ridingPaths);
                userService.updateOrderTrDingInfo(params);
                data.setState(ContentUtils.COMM_STATE_TRUE);
                return data;
            }else{
                data.setState(ContentUtils.COMM_STATE_TRUE);
                return data;
            }
        }
    }

    @RequestMapping(value = "/userRefund",method = RequestMethod.POST)
    @ResponseBody
    public ResponseData userRefund(HttpServletRequest request, HttpServletResponse response, int userId){
        ResponseData data = new ResponseData();
        boolean flag = orderService.updateUserPayDeposit(request,response,userId);
        if(flag){
            data.setState(ContentUtils.COMM_STATE_TRUE);
        }else {
            data.setState(ContentUtils.COMM_STATE_FALSE);
            data.setMsg("退款失败");
        }
        return data;
    }

}
